package controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import service.Utils;

@SuppressWarnings("serial")
public class WhoisServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		
		String name = req.getParameter("name");
		
		if(name!=null)
		{
			resp.setHeader( "Cache-Control", "public, max-age=86400");
			resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
			String content = "";
			try {
				
				URL url = new URL("http://www.whoismind.com/whois/"+Utils.fomatDomain(name)+".html");
	            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.setReadTimeout(500000);
				connection.setConnectTimeout(1000000);
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("utf-8")));
				char[] buf = new char[102102];
				int numRead=0;
		        while((numRead=reader.read(buf)) != -1){
		            String readData = String.valueOf(buf, 0, numRead);
		            content += readData;
		            buf = new char[102102];
		        }
		        reader.close();
	            Document doc = Jsoup.parse(content); 
	            System.out.println(doc);
	            String str  = doc.select("#whois-p1").html();
	            req.setAttribute("str", str);
	            req.setAttribute("name", name);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		try {
			req.getRequestDispatcher("/whois.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
